<template>
  <div v-if="getShow">
    <LoginFormTitle class="enter-x" />
    <Form class="p-4 enter-x" :model="formData" :rules="getFormRules" ref="formRef">
      <FormItem name="userName" class="enter-x">
        <Input
          size="middle"
          v-model:value="formData.userName"
          :placeholder="t('sys.login.userName')"
          class="fix-auto-fill"
        >
          <template #prefix>
            <Icon icon="ant-design:user-outlined" />
          </template>
        </Input>
      </FormItem>
      <FormItem name="nickName" class="enter-x">
        <Input
          size="middle"
          v-model:value="formData.nickName"
          :placeholder="t('sys.login.nickName')"
          class="fix-auto-fill"
        >
          <template #prefix>
            <Icon icon="carbon:user-simulation" />
          </template>
        </Input>
      </FormItem>
      <FormItem name="password" class="enter-x">
        <StrengthMeter
          size="middle"
          v-model:value="formData.password"
          :placeholder="t('sys.login.password')"
        >
          <template #prefix>
            <Icon icon="majesticons:lock-line" />
          </template>
        </StrengthMeter>
      </FormItem>
      <FormItem name="confirmPassword" class="enter-x">
        <InputPassword
          size="middle"
          visibilityToggle
          v-model:value="formData.confirmPassword"
          :placeholder="t('sys.login.confirmPassword')"
        >
          <template #prefix>
            <Icon icon="carbon-password" />
          </template>
        </InputPassword>
      </FormItem>

      <FormItem name="email" class="enter-x">
        <Input
          size="middle"
          v-model:value="formData.email"
          :placeholder="t('sys.login.email')"
          class="fix-auto-fill"
        >
          <template #prefix>
            <Icon icon="carbon-email" />
          </template>
        </Input>
      </FormItem>
      <FormItem name="mobile" class="enter-x">
        <Input
          size="middle"
          v-model:value="formData.mobile"
          :placeholder="t('sys.login.mobile')"
          class="fix-auto-fill"
        >
          <template #prefix>
            <Icon icon="clarity-mobile-phone-solid" />
          </template>
        </Input>
      </FormItem>
      <FormItem name="smsCode" class="enter-x">
        <CountdownInput
          size="default"
          v-model:value="formData.smsCode"
          :placeholder="t('sys.login.smsCode')"
          :sendCodeApi="handleSmsVerifyCode"
          icon="tabler:device-mobile-message"
          class="fix-auto-fill"
        >
          <template #prefix>
            <Icon icon="tabler:device-mobile-message" />
          </template>
        </CountdownInput>
      </FormItem>

      <FormItem name="organizationId" class="enter-x">
        <Input
          size="middle"
          v-model:value="formData.organizationId"
          :placeholder="t('sys.login.organizationId')"
          class="fix-auto-fill"
        >
          <template #prefix>
            <Icon icon="clarity-organization-line" />
          </template>
        </Input>
      </FormItem>

      <FormItem name="verifyCode" class="enter-x">
        <CaptchaInput
          size="default"
          v-model:value="formData.verifyCode"
          :placeholder="t('sys.login.verifyCode')"
          :getCaptchaApi="refreshVerifyCode"
          icon="iconoir:pc-check"
          class="fix-auto-fill"
        />
      </FormItem>

      <FormItem class="enter-x" name="policy">
        <!-- 没有逻辑，你需要自己处理（No logic, you need to deal with it yourself） -->
        <span>
          <Checkbox v-model:checked="formData.policy" size="small">
            {{ t('sys.app.policy') }}
          </Checkbox>
          <a target="_blank" @click="openRegistrationAgreementModal">
            {{ `《${t('sys.app.registrationAgreement')}》` }}
          </a>
          {{ `、` }}
          <a target="_blank" @click="openPrivacyPolicyModal">
            {{ `《${t('sys.app.privacyPolicy')}》` }}
          </a>
        </span>
      </FormItem>

      <Button
        type="primary"
        class="enter-x"
        size="middle"
        block
        @click="handleRegister"
        :loading="loading"
      >
        {{ t('sys.login.registerButton') }}
      </Button>
      <Button size="middle" block class="mt-4 enter-x" @click="handleBack">
        {{ t('sys.login.backSignIn') }}
      </Button>
    </Form>

    <BasicModal
      :destroyOnClose="true"
      :showOkBtn="false"
      @register="modalRegister"
      :title="modalTitle"
      width="50%"
      @height-change="modalHeightChange"
    >
      <template #insertFooter>
        <a-button type="primary" @click="printModalContent">{{ t('common.printText') }}</a-button>
      </template>
      <iframe
        :srcdoc="modalContent"
        width="100%"
        :height="modalIframeHeight"
        scrolling="no"
        seamless="true"
        sandbox="allow-same-origin"
        id="basicmodaliframe"
        ref="modalIframeRef"
      ></iframe>
    </BasicModal>
  </div>
</template>

<script lang="ts" setup>
  import { reactive, ref, toRaw, unref, computed, h } from 'vue';

  import LoginFormTitle from './LoginFormTitle.vue';
  import { Form, Input, Button, Checkbox } from 'ant-design-vue';
  import { StrengthMeter } from '@/components/StrengthMeter';
  import { CountdownInput } from '@/components/CountDown';
  import { CaptchaInput } from '@/components/Captcha';
  import Icon from '@/components/Icon/Icon.vue';
  import { useDesign } from '@/hooks/web/useDesign';

  import { useI18n } from '@/hooks/web/useI18n';
  import { useLoginState, useFormRules, useFormValid, LoginStateEnum } from './useLogin';

  import { useMessage } from '@/hooks/web/useMessage';
  import { isMobileNumber } from '@/enums/regexEnum';
  import { sendSmsVerifyCode } from '@/api/sms';
  import { getVerifyCode } from '@/api/sys';
  import { register } from '@/api/identity';

  import { BasicModal, useModal } from '@/components/Modal';
  import printJS from 'print-js';

  const FormItem = Form.Item;
  const InputPassword = Input.Password;

  const { t } = useI18n();
  const { prefixCls } = useDesign('login');
  const { handleBackLogin, handleAjaxResult, getLoginState } = useLoginState();
  const { createErrorModal } = useMessage();

  const formRef = ref();
  const loading = ref(false);

  const formData = reactive({
    userName: '',
    nickName: '',
    password: '',
    confirmPassword: '',
    email: '',
    mobile: '',
    smsCode: '',
    smsCodeId: '',
    organizationId: '',
    verifyCode: '',
    verifyCodeId: '',
    policy: false,
  });

  const { getFormRules } = useFormRules(formData);
  const { validForm } = useFormValid(formRef);

  const getShow = computed(() => unref(getLoginState) === LoginStateEnum.REGISTER);

  // var iframes = document.getElementsByTagName('iframe');
  // setInterval(function () {
  //   console.log('iframes', iframes);
  //   for (var i = 0, j = iframes.length; i < j; ++i) {
  //     iframes[i].setAttribute('height', iframes[i].contentWindow.document.body.scrollHeight);
  //   }
  // }, 1000);

  const modalIframeRef = ref<HTMLElement | null>(null);
  const modalTitle = ref('');
  const modalContent = ref<string>();
  const modalIframeHeight = ref('100%');
  const [modalRegister, { openModal: openModal }] = useModal();
  /** 打开注册协议 */
  function openRegistrationAgreementModal() {
    modalTitle.value = t('sys.app.registrationAgreement');
    modalContent.value = t('registration_agreement.content');
    openModal();

    // //延时执行
    // setTimeout(() => {
    //   const iframe = window.frames['basicmodaliframe'];
    //   //获得body
    //   const body = iframe?.contentWindow?.document?.body;
    //   // console.log('iframes-body', body);
    //   // console.log('iframes-body-xy', {
    //   //   clientWidth: body?.clientWidth,
    //   //   clientHeight: body?.clientHeight,
    //   //   offsetWidth: body?.offsetWidth,
    //   //   offsetHeight: body?.offsetHeight,
    //   // });
    //   modalIframeHeight.value = body?.clientHeight || body?.offsetHeight;
    // }, 100);
  }
  /** 打开隐私政策 */
  function openPrivacyPolicyModal() {
    modalTitle.value = t('sys.app.privacyPolicy');
    modalContent.value = t('privacy_policy.content', { email: t('sys.app.contactEmail') });
    openModal();
  }
  /** 对话框窗体高度改变 */
  function modalHeightChange() {
    //延时执行
    setTimeout(() => {
      const iframe = window.frames['basicmodaliframe'];
      //获得body
      const body = iframe?.contentWindow?.document?.body;
      // console.log('iframes-body', body);
      // console.log('iframes-body-xy', {
      //   clientWidth: body?.clientWidth,
      //   clientHeight: body?.clientHeight,
      //   offsetWidth: body?.offsetWidth,
      //   offsetHeight: body?.offsetHeight,
      // });
      const height = (body?.clientHeight || body?.offsetHeight || 400) + 50;
      if (modalIframeHeight.value != height) {
        modalIframeHeight.value = height;
      }
    }, 100);
  }
  /** 打印对话窗内容 */
  function printModalContent() {
    const iframe = window.frames['basicmodaliframe'];
    //获得document
    const document = iframe?.contentDocument;
    // console.log('document', document?.querySelector('html'));
    printJS({
      printable: document?.querySelector('html'),
      type: 'html',
      documentTitle: modalTitle.value, // 文档标题。
      scanStyles: false, // 设置为false时，库将不处理应用于正在打印的html的样式。使用css参数时很有用
      // showModal: true, // 启用此选项可在检索或处理大型PDF文件时显示用户反馈。
    });
  }

  /** 处理注册 */
  async function handleRegister() {
    const data = await validForm();
    if (!data) return;
    //console.log(data);
    try {
      loading.value = true;
      const dto = toRaw({
        UserName: formData.userName,
        NickName: formData.nickName,
        Password: formData.password,
        ConfirmPassword: formData.confirmPassword,
        Email: formData.email,
        EmailConfirmUrl: `${window.location.origin}/#/confirm-email`,
        PhoneNumber: formData.mobile,
        SmsCode: formData.smsCode,
        SmsCodeId: formData.smsCodeId,
        OrganizationId: formData.organizationId,
        VerifyCode: formData.verifyCode,
        VerifyCodeId: formData.verifyCodeId,
      });
      const ajaxResult = await register(dto);
      if (ajaxResult.Succeeded) {
        clearFormData();
        handleAjaxResult(ajaxResult, LoginStateEnum.REGISTER_RESULT);
      } else {
        showErrorModal(t('sys.api.errorTip'), ajaxResult.Content);
      }
    } catch (error: any) {
      showErrorModal(t('sys.api.errorTip'), error?.message || t('sys.api.networkExceptionMsg'));
    } finally {
      loading.value = false;
    }
  }

  /** 处理返回 */
  async function handleBack() {
    clearFormData();
    handleBackLogin();
  }

  /** 处理短信验证码 */
  async function handleSmsVerifyCode() {
    if (formData.mobile === undefined || formData.mobile === null || formData.mobile === '') {
      showErrorModal(t('sys.api.errorTip'), t('sys.login.mobilePlaceholder'));
      return false;
    }
    if (!isMobileNumber(formData.mobile)) {
      showErrorModal(t('sys.api.errorTip'), t('sys.login.mobileFormatError'));
      return false;
    }
    try {
      const dto = toRaw({ PhoneNumber: formData.mobile, mode: 'none' });
      const ajaxResult = await sendSmsVerifyCode(dto);
      if (!ajaxResult.Succeeded) {
        showErrorModal(t('sys.api.errorTip'), ajaxResult.Content);
        return false;
      }
      formData.smsCodeId = ajaxResult.Data as string;
      return true;
    } catch (error: any) {
      showErrorModal(t('sys.api.errorTip'), error?.message || t('sys.api.networkExceptionMsg'));
      return false;
    }
  }

  /** 刷新验证码 */
  async function refreshVerifyCode() {
    const verifyCodeDto = await getVerifyCode();
    // console.log('VerifyCode', verifyCodeDto);
    formData.verifyCodeId = verifyCodeDto.Id;
    return verifyCodeDto.Image;
  }

  /** 清除表单数据 */
  function clearFormData() {
    formData.userName = '';
    formData.nickName = '';
    formData.password = '';
    formData.confirmPassword = '';
    formData.email = '';
    formData.mobile = '';
    formData.smsCode = '';
    formData.smsCodeId = '';
    formData.organizationId = '';
    formData.verifyCode = '';
    formData.verifyCodeId = '';
    formData.policy = false;
  }

  function showErrorModal(title: string, content: string) {
    createErrorModal({
      zIndex: 999999999,
      title: () => h('span', title),
      content: () => h('span', content),
      getContainer: () => document.body.querySelector(`.${prefixCls}`) || document.body,
    });
  }
</script>

<style lang="less" scoped>
  iframe {
    border: 0;
    background-color: transparent;
  }

  [data-theme='dark'] iframe {
    background-color: #cecece4d;
  }
</style>
